package com.zzh.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.hunter2.standard.entity.Cv;
import com.hunter2.standard.entity.CvBasic;
import com.hunter2.standard.entity.CvComment;
import com.hunter2.standard.entity.CvEducation;
import com.hunter2.standard.entity.CvExpectation;
import com.hunter2.standard.entity.CvJob;
import com.hunter2.standard.entity.CvProject;
import com.hunter2.standard.entity.CvSkill;
import com.zph.entity.BasicNow;
import com.zph.entity.CVObject;
import com.zph.entity.Comment;
import com.zph.entity.Constants;
import com.zph.entity.EducationNow;
import com.zph.entity.Expectation;
import com.zph.entity.Job;
import com.zph.entity.Project;
import com.zph.entity.Skill;
import com.zph.exception.FileOverSizeException;
import com.zph.service.ServiceStart;

/**
 * @Des 批量解析
 * @author 张振华
 * @date 2017年3月27日 下午2:51:32
 * @version v1.0
 */
public class ReadDir {

	ServiceStart service = new ServiceStart();
	// 简历完整度
	public static final int total = 90;// 完整度积分
	public static int integrityCount = 0; // 完整度
	// public static Double integrity = 0.00;// 相对完整度
	DecimalFormat df = new DecimalFormat("#0.00");

	// 连接数据库
	public static final String IP = "rm-2zeeg6302tb7oqv57o.mysql.rds.aliyuncs.com";
	public static final String driver = "com.mysql.jdbc.Driver";
	public static final String url = "jdbc:mysql://" + IP
			+ ":3306/hunter2?zeroDateTimeBehavior=convertToNull&useSSL=false";
	public static final String user = "czhd";
	public static final String password = "Czhd1234";
	static Connection connect = null;
	public static final String cv_sql = "select *from cv order by id desc limit 1";
	public static HashMap<String, Integer> m_UserDic = new HashMap<String, Integer>(200, 0.75f); // 词典
	static int candidateid = 0;
	
	
	static String num = "2011";
	
	//本地路径
	static String dir = "E:/cv/"+num; 
	static String readDir="E:/2015年购买/"+num+""; 
	
	//远程路径
//	static String dir = "/home/data/cv/db";   
//	static String readDir="/home/data/cv/unzip/"+num; 
	
	static String pa_cv = dir + "/cv.txt";
	static String pa_basic = dir + "/basic.txt";
	static String pa_exp = dir + "/exp.txt";
	static String pa_edu = dir + "/edu.txt";
	static String pa_job = dir + "/job.txt";
	static String pa_pro = dir + "/pro.txt";
	static String pa_skill =dir + "/skill.txt"; 
	static String pa_com = dir + "/com.txt";
	static String pa_credit = dir + "/credit.txt"; 
	static String pa_erro = dir+"/erro.txt";
	

	
 
	
	// 读写
	static FileWriter fw_cv;
	static FileWriter fw_basic;
	static FileWriter fw_exp;
	static FileWriter fw_edu;
	static FileWriter fw_job;
	static FileWriter fw_pro;
	static FileWriter fw_skill;
	static FileWriter fw_com;
	static FileWriter fw_credit;
	// 出错记录
	static FileWriter fw_erro;

	static {
		init(Constants.CreditReport_new);
		try {
			// 连接数据库
			Class.forName(driver);
			connect = DriverManager.getConnection(url, user, password);
			// 获取初始候选人id
			PreparedStatement ps = connect.prepareStatement(cv_sql);
			ResultSet rs = ps.executeQuery();
			if (rs.next()) {
				candidateid = rs.getInt("id") + 5;
			}
			
			// 初始化读写
			fw_cv = new FileWriter(pa_cv, true);
			fw_basic = new FileWriter(pa_basic, true);
			fw_exp = new FileWriter(pa_exp, true);
			fw_edu = new FileWriter(pa_edu, true);
			fw_job = new FileWriter(pa_job, true);
			fw_pro = new FileWriter(pa_pro, true);
			fw_skill = new FileWriter(pa_skill, true);
			fw_com = new FileWriter(pa_com, true);

			fw_credit = new FileWriter(pa_credit, true);

			fw_erro = new FileWriter(pa_erro, true);

		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}

	public static void main(String[] args) {

		ReadDir rd = new ReadDir();

		long t1 = System.currentTimeMillis();
		// rd.readDir("F:/test");
		 rd.readDir(readDir); //E:\2015年购买\2015\9
//		rd.readDir("E:/2015年购买/2015/9");
		long t2 = System.currentTimeMillis();
		System.out.println((t2 - t1) / 1000 + " s");
	}

	private static int init(String fileName) {

		InputStream in = null;
		String[] str = null;
		if (fileName != null && !fileName.equals("")) {
			try {
				in = Constants.class.getResourceAsStream(fileName);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			return 1;
		}
		try {
			String tempStr = "";
			BufferedReader read = new BufferedReader(new InputStreamReader(in, "UTF-8"));
			while ((tempStr = read.readLine()) != null) {
				// System.out.println(tempStr);
				str = tempStr.split(",|/");
				m_UserDic.put(str[0], Integer.parseInt(str[1]));
			}
			str = null;
			tempStr = null;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in!= null) {
					in.close();
					in = null;
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return 0;

	}

	public void readDir(String dir) {

		File filedir = new File(dir);
		if (filedir.isDirectory()) {

			for (final String name : filedir.list()) {
				// 拼凑路径
				final String path = dir + "/" + name;
				try {
					File file2 = new File(path);
					if (file2.isDirectory()) {
						readDir(path);
					} else { // 超时设置
						System.out.println("---------------begin------------------");
						ExecutorService exec = Executors.newFixedThreadPool(1);

						Callable<String> call = new Callable<String>() {
							public String call() throws Exception {

								// 文件调用解析
								System.out.println(name);
								CVObject map = service.PLparseCv(path);
								// 计算简历完整度
								float integrity = computeIntegrity(map);
								double total_score = 0.0f;
								// 计算征信分
								if (integrity > 20) {
									total_score = computeCreditReport(map, candidateid);
									// 持久化
									write2txt(map, (int) integrity, total_score);
									candidateid++;
								}

								return "线程执行完成.";
							}
						};

						try {
							Future<String> future = exec.submit(call);
							String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为
																						// 1
																						// 秒
							System.out.println("任务成功返回:" + obj);
						} catch (FileOverSizeException ex) {
							fw_erro.write("文件过大--" + path + "\r\n");
							fw_erro.flush();
							ex.printStackTrace();
						} catch (TimeoutException ex) {
							fw_erro.write("处理超时--" + path + "\r\n");
							fw_erro.flush();
							ex.printStackTrace();
						} catch (Exception e) {
							fw_erro.write("处理失败--" + path + "\r\n");
							fw_erro.flush();
							e.printStackTrace();
						}
						// 关闭线程池
						exec.shutdown();

					}
				} catch (Exception e) {
					try {
						fw_erro.write("未知--" + path + "\r\n");
						fw_erro.flush();

					} catch (IOException e1) {
						e1.printStackTrace();
					}
					e.printStackTrace();
				}
			}

		}
	}

	/**
	 * 计算简历完整度
	 */
	private float computeIntegrity(CVObject map) {

		integrityCount = 0;

		BasicNow basic = map.getBasic();

		// 基本信息完整度 21 total:50分
		if (basic.getName() != null && !basic.getName().trim().equals("")) {
			integrityCount += 2;
		}
		if (0 != basic.getGender()) {
			integrityCount += 2;
		}
		if (basic.getIdCard() != null && !basic.getIdCard().trim().equals("")) {
			integrityCount += 4;
		}
		if (basic.getCompany() != null && !basic.getCompany().trim().equals("")) {
			integrityCount += 2;
		}
		if (basic.getTitle() != null && !basic.getTitle().trim().equals("")) {
			integrityCount += 2;
		}
		if (basic.getCity() != null && !basic.getCity().trim().equals("")) {
			integrityCount += 2;
		}
		if (basic.getBirthPlace() != null && !basic.getBirthPlace().trim().equals("")) {
			integrityCount += 2;
		}
		if ((basic.getPhone() != null && !basic.getPhone().trim().equals(""))
				|| basic.getMobile() != null && !basic.getMobile().trim().equals("")) {
			integrityCount += 4;
		}

		if (basic.getEmail() != null && !basic.getEmail().trim().equals("")) {
			integrityCount += 4;
		}
		if (basic.getAge() != null && !basic.getAge().trim().equals("")) {
			integrityCount += 2;
		}
		if (basic.getBirthday() != null && !basic.getBirthday().trim().equals("")) {
			integrityCount += 2;
		}
		if (0 != basic.getMarriage()) {
			integrityCount += 2;
		}
		if (basic.getDegree() != null) {
			integrityCount += 2;
		}
		if (basic.getJob_time() != null) {
			integrityCount += 4;
		}
		if (basic.getJobStatus() != null) {
			integrityCount += 2;
		}
		if (basic.getCurrentSalary() != null && !basic.getCurrentSalary().trim().equals("")) {
			integrityCount += 2;
		}
		if (basic.getAddress() != null && !basic.getAddress().trim().equals("")) {
			integrityCount += 2;
		}
		// com
		if (basic.getPreference() != null && !basic.getPreference().trim().equals("")) {
			integrityCount += 2;
		}

		// 期望信息
		Expectation exp = map.getExpectation();
		if (exp != null) {
			if (exp.getExpectationSalary() != null) {
				integrityCount += 2;
			}
			if (exp.getExpectationCityId() != null) {
				integrityCount += 2;
			}
			if (exp.getExpectationTitle() != null && !exp.getExpectationTitle().trim().equals("")) {
				integrityCount += 2;
			}
		}

		// 教育经历
		List<EducationNow> educations = map.getEducations();
		if (educations != null)
			for (int i = 0; i < educations.size(); i++) {

				if (0 == i)
					integrityCount += 8;
				else if (i < 3)
					integrityCount += 1;

			}

		// 工作经历
		List<Job> jobs = map.getJobs();
		if (jobs != null)
			for (int i = 0; i < jobs.size(); i++) {

				if (0 == i)
					integrityCount += 8;
				else if (i < 3)
					integrityCount += 1;

			}

		// 项目经历
		List<Project> projects = map.getProjects();
		if (projects != null)
			for (int i = 0; i < projects.size(); i++) {

				if (0 == i)
					integrityCount += 8;
				else if (i < 3)
					integrityCount += 1;

			}

		// 技能
		List<Skill> skills = map.getSkills();
		if (skills != null)
			for (int i = 0; i < skills.size(); i++) {

				if (0 == i)
					integrityCount += 8;
				else if (i < 3)
					integrityCount += 1;

			}

		// 评论
		List<Comment> comments = map.getComments();
		if (comments != null && comments.get(0) != null && comments.get(0).getCommentInfo() != null) {
			integrityCount += 6;
		}

		// 计算简历完整度
		float integrity = Float.parseFloat(df.format((double) integrityCount / 90)) * 100;

		return integrity;
	}

	/**
	 * 计算征信分
	 */

	private double computeCreditReport(CVObject map, int candidateid) {
		boolean flag = false;
		if (null == map)
			return 0.0f;
		// 获取到学校的征信排名分
		String basic_school = null;
		String basic_degree = "0";
		String basic_major = null;
		String basic_company = null;
		String basic_title = null;
		String skill_separate = "";
		String id_card = "";
		String execute_ids = "";
		String shixin_ids = "";
		double score_education = 300.0;// start line 300
		double score_job = 400.0;
		double score_skill = 400.0;
		double score_identity = 300.0;// start line 300
		double score_relationship = 400.0;// start line 300
		double score_history = 400.0;// start line 300
		int job_time = 0;
		double score_school = 0.6;
		double score_degree = 0.0;
		String max_school = null;
		int max_degree = 1;
		try {
			String m6 = map.getBasic().getName();// name
			id_card = map.getBasic().getIdCard(); // id_card
			String m12 = map.getBasic().getCompany(); // company
			basic_company = m12;

			String m13 = map.getBasic().getTitle(); // title
			basic_title = m13;

			String m22 = map.getBasic().getMajor(); // major
			basic_major = m22;

			String m23 = map.getBasic().getDegree().getId() + ""; // degree
			if (m23 != null && !m23.equals(""))
				basic_degree = m23;

			String m24 = map.getBasic().getSchool(); // school
			basic_school = m24;

			String m56 = "0";
			if (map != null && map.getBasic() != null && map.getBasic().getJob_time() != null)
				m56 = map.getBasic().getJob_time().toString(); // job_time
			if (m56 != null)
				job_time = Integer.parseInt(m56);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("征信分计算失败");
		}
		System.out.println("基本资料信息计算完毕");
		try {
			List<EducationNow> educations = map.getEducations();
			if (educations != null)
				for (EducationNow education : educations) {
					String m8 = education.getSchool(); // school
					String m9 = education.getMajor(); // major
					int m10 = education.getDegree().getId(); // degree
					if (m10 >= max_degree) {
						max_degree = m10;
						score_school = getScoreBySchoolName(m8);
					}
				}
			score_degree = (max_degree - 1) * 100;
			score_education = score_degree + 500 * score_school;

			if (score_education == 0) {
				if (Integer.parseInt(basic_degree) != 0)
					score_degree = (Integer.parseInt(basic_degree) - 1) * 100;
				if (Integer.parseInt(basic_degree) == 0)
					score_degree = 0;
				if (basic_school != null && !basic_school.equals(""))
					score_school = getScoreBySchoolName(basic_school);
				score_education = score_degree + 500 * score_school;
			}
			if (score_education > 1000)
				score_education = 1000;
			if (score_education < 300)
				score_education = 300;

		} catch (Exception e) {
			System.out.println("征信分教育经历计算失败");
			e.printStackTrace();
		}
		System.out.println("教育经历征信分计算完毕-education score = " + score_education);

		// 工作经历
		try {
			List<Job> jobs = map.getJobs();
			if (jobs != null)
				for (Job job : jobs) {
					double score_job_time = 0;
					double score_company = 0;
					int m6 = 0;// 开始时间
					if (null != job.getStartTime() || !"".equals(job.getStartTime()) || job.getStartTime().length() > 4)
						m6 = Integer.parseInt(job.getStartTime().substring(0, 3));// 开始时间
					int m7 = 0;// 结束时间
					if (null != job.getEndTime() || !"".equals(job.getEndTime()) || job.getEndTime().length() > 4)
						m7 = Integer.parseInt(job.getEndTime().substring(0, 3));// 结束时间
					String m8 = job.getCompany(); // 公司
					String m9 = job.getDepartment(); // 部门
					String m10 = job.getTitle(); // 职位
					if (m_UserDic.containsKey(m8)) {
						int type = m_UserDic.get(m8);
						if (type >= 5001001 && type <= 5001501) {
							score_company = 500 - (type - 5001001) * (50.0 / 501);
							if (m7 - m6 < 1) {
								score_job_time = 0.6;
							} else if ((m7 - m6 >= 1) && (m7 - m6 < 2)) {
								score_job_time = 0.7;
							} else if ((m7 - m6 >= 2) && (m7 - m6 < 3)) {
								score_job_time = 0.8;
							} else if ((m7 - m6 >= 3) && (m7 - m6 < 4)) {
								score_job_time = 1;
							} else if ((m7 - m6 >= 4) && (m7 - m6 < 5)) {
								score_job_time = 0.9;
							} else if ((m7 - m6 >= 5)) {
								score_job_time = 0.8;
							}
							score_job += score_company * score_job_time * 0.2;
						} else if (type >= 5002001 && type <= 5002457) {
							score_company = 450 - (type - 5002001) * (50.0 / 457);
							if (m7 - m6 < 1) {
								score_job_time = 0.6;
							} else if ((m7 - m6 >= 1) && (m7 - m6 < 2)) {
								score_job_time = 0.7;
							} else if ((m7 - m6 >= 2) && (m7 - m6 < 3)) {
								score_job_time = 0.8;
							} else if ((m7 - m6 >= 3) && (m7 - m6 < 4)) {
								score_job_time = 1;
							} else if ((m7 - m6 >= 4) && (m7 - m6 < 5)) {
								score_job_time = 0.9;
							} else if ((m7 - m6 >= 5)) {
								score_job_time = 0.8;
							}
							score_job += score_company * score_job_time * 0.2;
						} else {
							score_company = 400.0 - Math.random() * 10.0;
							if (m7 - m6 < 1) {
								score_job_time = 0.6;
							} else if ((m7 - m6 >= 1) && (m7 - m6 < 2)) {
								score_job_time = 0.7;
							} else if ((m7 - m6 >= 2) && (m7 - m6 < 3)) {
								score_job_time = 0.8;
							} else if ((m7 - m6 >= 3) && (m7 - m6 < 4)) {
								score_job_time = 1;
							} else if ((m7 - m6 >= 4) && (m7 - m6 < 5)) {
								score_job_time = 0.9;
							} else if ((m7 - m6 >= 5)) {
								score_job_time = 0.8;
							}
							score_job += score_company * score_job_time * 0.2;
						}
					} else {
						score_company = 400.0 - Math.random() * 10.0;
						if (m7 - m6 < 1) {
							score_job_time = 0.6;
						} else if ((m7 - m6 >= 1) && (m7 - m6 < 2)) {
							score_job_time = 0.7;
						} else if ((m7 - m6 >= 2) && (m7 - m6 < 3)) {
							score_job_time = 0.8;
						} else if ((m7 - m6 >= 3) && (m7 - m6 < 4)) {
							score_job_time = 1;
						} else if ((m7 - m6 >= 4) && (m7 - m6 < 5)) {
							score_job_time = 0.9;
						} else if ((m7 - m6 >= 5)) {
							score_job_time = 0.8;
						}
						score_job += score_company * score_job_time * 0.2;
					}
				}
			if (score_job > 1000)
				score_job = 1000;
			if (score_job == 400) {// 没有工作经历，从基本信息中提取
				double score_company = 0;
				double score_job_time = 0.6;
				if (m_UserDic.containsKey(basic_company)) {
					int type = m_UserDic.get(basic_company);
					if (type >= 5001001 && type <= 5001501) {
						score_company = 500 - (type - 5001001) * (50.0 / 501);
						score_job += score_company * score_job_time * 0.2;
					} else if (type >= 5002001 && type <= 5002457) {
						score_company = 450 - (type - 5002001) * (50.0 / 457);
						score_job += score_company * score_job_time * 0.2;
					} else {
						score_company = 400.0 - Math.random() * 10.0;
						score_job += score_company * score_job_time * 0.2;
					}
				} else {
					score_company = 400.0 - Math.random() * 10.0;
					score_job += score_company * score_job_time * 0.2;
				}
			}
			if (score_job < 300)
				score_job = 300;
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("计算工作经历信息失败");
		}
		try {
			List<Skill> skills = map.getSkills();
			int num = 0;
			if (skills != null)
				for (Skill skill : skills) {
					double experience = 0;
					double skill_info = 0;
					String m1 = skill.getId() + "";// id
					String m6 = skill.getSkillName();// skill_name
					String m9 = skill.getSkillInfo();// skill_info
					int m11 = skill.getSkillExperience();// skill_experience
					if (m9 != null) {
						if (m9.equals("了解")) {
							skill_info = 80 + Math.random();
						} else if (m9.equals("一般") || m9.equals("熟悉") || m9.equals("熟练")) {
							skill_info = 120 + Math.random();
						} else if (m9.equals("良好")) {
							skill_info = 160 + Math.random();
						} else if (m9.equals("精通")) {
							skill_info = 200 + Math.random();
						} else {
							skill_info = 20 + Math.random();
						}
					}
					if (m11 < 6) {
						experience = 0.6 - (5 - m11) * (0.1 / 6);
					} else if ((m11 >= 6) && (m11 < 12)) {
						experience = 0.7 - (11 - m11) * (0.1 / 6);
					} else if ((m11 >= 12) && (m11 < 18)) {
						experience = 0.8 - (17 - m11) * (0.1 / 6);
					} else if ((m11 >= 18) && (m11 < 24)) {
						experience = 0.9 - (23 - m11) * (0.1 / 6);
					} else if ((m11 >= 24)) {
						experience = 0.9 + (m11 - 24) * (0.002);
					} else {
						experience = 0.4;
					}
					score_skill += skill_info * experience;
					if ((skill_info * experience * 3.5 + 400) > 1000) {
						if (skill_separate.length() < 1000) {
							skill_separate += m1 + "," + (1000 * 0.2 + score_education * 0.4 + score_job * 0.4) + ";";
						}
					} else {
						if (skill_separate.length() < 1000) {
							skill_separate += m1 + "," + ((skill_info * experience * 3.5 + 400) * 0.2
									+ score_education * 0.4 + score_job * 0.4) + ";";
						}
					}
					num++;
				}
			if (score_skill > 1000)
				score_skill = 1000;
			if (score_skill > 0)
				score_skill = score_education * 0.4 + score_job * 0.4 + score_skill * 0.2;
			if (score_skill < 300)
				score_skill = 300;
			// 可以将查找到的值写入类，然后返回相应的对象
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("技能征信分计算失败");
		}

		if (null != map && null != map.getBasic() && null != map.getBasic().getIdCard()
				&& !"".equals(map.getBasic().getIdCard())) {
			String sql = "select * from shixin where partyCardNum='" + id_card + "'";

			try {
				Statement stmt = connect.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				int num = 0;
				while (rs.next()) {
					if (execute_ids.length() < 1000) {
						execute_ids += rs.getInt(1) + ";";
					}
					num++;
				}
				score_history = score_history - num * 10;
				if (score_history > 1000) {
					score_history = 1000;
				}
				if (score_history < 300)
					score_history = 300;
			} catch (Exception e) {
				e.printStackTrace();
			}

			sql = "select * from cv_credit_record where cv_id=" + candidateid;
			try {
				// System.out.println("shixin");
				Statement stmt = connect.createStatement();
				ResultSet rs = stmt.executeQuery(sql);
				int num = 0;
				while (rs.next()) {
					shixin_ids += rs.getInt(1) + ";";
					num++;
				}
				score_history = score_history - num * 5;
				if (score_history > 1000) {
					score_history = 1000;
				}
				if (score_history <= 0) {
					score_history = 0;
				}
			} catch (Exception e) {
				e.printStackTrace();
				System.out.println("被执行人计算征信分失败");
			}

		}

		// 征信分转换
		double score_history_new = score_history * 0.4 + score_education * 0.3 + score_job * 0.3;
		double score_relationship_new = score_relationship * 0.2 + score_education * 0.4 + score_job * 0.4;

		double total_score = create(candidateid, score_education, score_skill, score_job, score_history_new,
				score_relationship_new, job_time, skill_separate, execute_ids, shixin_ids);

		return total_score;
	}

	private double create(int candidateid, double education_score, double skill_score, double job_score,
			double history_score, double relationship_score, int job_time, String skill_separate, String execute_ids,
			String shixin_ids) {
		double total_score = 0;
		try {
			double score_education = (education_score);
			double score_skill = (skill_score);
			double score_job = (job_score);
			double score_history = (history_score);
			double score_relationship = (relationship_score);
			int shixin_param = 100; // 100 -> 36.8
			int skill_param = 100;
			int relationship_param = 100;

			double job_rate = 0.5;
			double education_rate = 0.5;
			if (job_time > 5) {
				job_time = 5;
			} else if (job_time < 1) {
				job_time = 1;
			}
			job_rate = 1 - (5 - job_time) * 0.1 - 0.3;
			education_rate = (5 - job_time) * 0.1 + 0.3;
			total_score = (300 + (score_education * education_rate + score_job * job_rate) * 0.6
					+ skill_param * (skill_score / 1000.0) * Math.pow(Math.E, -(skill_score / 1000.0))
					+ relationship_param * (relationship_score / 1000.0)
							* Math.pow(Math.E, -(relationship_score / 1000.0))
					- shixin_param * ((1000 - history_score) / 1000.0)
							* Math.pow(Math.E, -((1000 - history_score) / 1000.0)));
			System.out.println("create-征信总分：" + total_score);
			// Date date = new Date();
			// DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// String time = format.format(date);

			if (total_score > 1000)
				total_score = 1000;

			// 打印征信单

			String line = "\\N" + "\t" //
					+ candidateid + "\t" //
					+ total_score + "\t" //
					+ total_score + "\t" //
					+ score_relationship + "\t"//
					+ score_history + "\t" //
					+ score_education + "\t" //
					+ score_skill + "\t" //
					+ score_job + "\t" //
					+ 1 + "\t" //
					+ "\\N" + "\t"//
					+ "\\N" + "\t" //
					+ "\\N" + "\t" //   skill_separate 无法获取id ,暂时禁用
					+ execute_ids + "\t" //
					+ shixin_ids + "\t";
			System.out.println("征信分：" + line);
			fw_credit.write(line + "\r\n");
			fw_credit.flush();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return total_score;
	}

	private double getScoreBySchoolName(String name) {
		// double school_score = 0.6 + Math.random() * 0.02 - 0.01;
		double school_score = 0.0;
		String sql = "select * from university_rank where name='" + name + "'";
		try {
			Statement stmt = connect.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				school_score = rs.getDouble(5);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return school_score;
	}

	/**
	 * 写入txt文档
	 * 
	 * @param integrity
	 * @param total_score
	 */
	private void write2txt(CVObject map, int integrity, double total_score) {

		try {
			// cv
			Cv cv = new Cv();
			cv.setId(candidateid);
			cv.setIntegrity(integrity);
			fw_cv.write(cv.write2Line(cv) + "\r\n");
			fw_cv.flush();

			// 基本信息
			if (map.getBasic() != null) {
				BasicNow bic = map.getBasic();
				CvBasic cvbic = new CvBasic();
				cvbic.setCandidateid(candidateid);
				cvbic.setName(changeNull(bic.getName()));
				cvbic.setUsedname("\\N");
				cvbic.setEnglishname("\\N");
				cvbic.setGender(bic.getGender());
				cvbic.setCardtype(bic.getCardType());
				cvbic.setIdcard(changeNull(bic.getIdCard()));
				cvbic.setCompany(changeNull(bic.getCompany()));
				cvbic.setTitle(changeNull(bic.getTitle()));
				cvbic.setCity(changeNull(bic.getCity()));
				cvbic.setBirthPlace(changeNull(bic.getBirthPlace()));
				cvbic.setPhone(changeNull(bic.getPhone()));
				cvbic.setMobile(changeNull(bic.getMobile()));
				cvbic.setEmail(changeNull(bic.getEmail()));
				cvbic.setAge(changeNull(bic.getAge()));
				cvbic.setBirthday(changeNull(bic.getBirthday()));
				cvbic.setMarriage(bic.getMarriage());
				cvbic.setMajor(changeNull(bic.getMajor()));
				cvbic.setDegree(bic.getDegree().getId());
				cvbic.setSchool(changeNull(bic.getSchool()));
				if (bic.getJob_time() != null && bic.getJob_time() != 0) {
					long work_experience_long = bic.getJob_time();
					int work_experience_int = (int) work_experience_long;
					String str_25;
					if (work_experience_int != 0) {

						if (work_experience_int < 1) {// 年
							str_25 = "102";
						} else if (work_experience_int >= 1 && work_experience_int < 3) {
							str_25 = "103";
						} else if (work_experience_int >= 3 && work_experience_int < 5) {
							str_25 = "104";
						} else if (work_experience_int >= 5 && work_experience_int < 10) {
							str_25 = "11";
						} else if (work_experience_int >= 10) {
							str_25 = "12";
						} else {
							str_25 = "102";
						}
						cvbic.setJobtime(str_25);
						cvbic.setJobTime(work_experience_int);
					} else {
						cvbic.setJobtime("102");
						cvbic.setJobTime(0);
					}
				} else {
					cvbic.setJobtime("102");
					cvbic.setJobTime(0);
				}
				cvbic.setHeight("\\N");
				cvbic.setWeight("\\N");
				cvbic.setBwh("\\N");
				cvbic.setNationality("\\N");
				cvbic.setCountry("\\N");

				cvbic.setHealth("\\N");
				cvbic.setPolitics(changeNull(bic.getPolitics()));
				cvbic.setJobStatus(bic.getJobStatus().getId());
				cvbic.setCurrentSalary(changeNull(bic.getCurrentSalary()));
				cvbic.setExpectedSalary(bic.getExpectedSalary().getId());
				cvbic.setExpectedCity(changeNull(bic.getExpectedCity()));
				cvbic.setExpectedJob(changeNull(bic.getExpectedJob()));
				cvbic.setWeixin("\\N");
				cvbic.setQq("\\N");
				cvbic.setLinkedin(changeNull("\\N"));
				cvbic.setDajie("\\N");
				cvbic.setWeibo("\\N");
				cvbic.setScore(0.0f);
				cvbic.setBasicInfo(changeNull(bic.getBasicInfo()));
				cvbic.setAddress(changeNull(bic.getAddress()));
				cvbic.setTradeId(bic.getTradeId());
				cvbic.setFunctionId(bic.getFunctionId().getId());
				cvbic.setMpc(bic.getMpc());
				// cvbic.setPhotoId(bic.getPhotoId());
				cvbic.setComment(changeNull(bic.getComment()));
				cvbic.setPreference(changeNull(bic.getPreference()));
				cvbic.setFlag(1);
				// cvbic.setFileid(0);
				cvbic.setOwnerid(0);
				cvbic.setCompanyId(1);
				// cvbic.setJobTime(jobTime);
				// cvbic.setWorkYear("");
				cvbic.setIntegrity(integrity);
				cvbic.setTotal_score(total_score + "");
				fw_basic.write(cvbic.write2Line2(cvbic) + "\r\n");
				fw_basic.flush();

			}
			// 期望信息
			if (map.getExpectation() != null) {
				Expectation exp = map.getExpectation();
				CvExpectation cvexp = new CvExpectation();
				cvexp.setCandidateid(candidateid);
				if (exp.getExpectationSalary() != null)
					cvexp.setExpectationSalary((int) (long) exp.getExpectationSalary());
				if (exp.getPresentSalary() != null)
					cvexp.setPresentSalary((int) (long) exp.getPresentSalary());
				cvexp.setExpectationCompany(changeNull(exp.getExpectationCompany()));
				cvexp.setExpectationTitle(changeNull(exp.getExpectationTitle()));
				if (exp.getExpectationIndustryId() != null)
					cvexp.setExpectationIndustryId(changeNull(exp.getExpectationIndustryId() + ""));
				else
					cvexp.setExpectationIndustryId("\\N");
				if (exp.getExpectationCityId() != null)
					cvexp.setExpectationCityId(changeNull(exp.getExpectationCityId() + ""));
				else
					cvexp.setExpectationCityId("\\N");
				fw_exp.write(cvexp.write2Line(cvexp) + "\r\n");
				fw_exp.flush();
			}

			// 教育信息
			if (map.getEducations() != null) {
				List<EducationNow> edus = map.getEducations();
				for (EducationNow edu : edus) {
					CvEducation cvedu = new CvEducation();
					cvedu.setCandidateid(candidateid);
					cvedu.setStartTime(changeNull(edu.getStartTime()));
					cvedu.setEndTime(changeNull(edu.getEndTime()));
					cvedu.setSchool(changeNull(edu.getSchool()));
					cvedu.setMajor(changeNull(edu.getMajor()));
					cvedu.setDegree(edu.getDegree().getId());
					cvedu.setInfo(changeNull(edu.getInfo()));
					cvedu.setEducationInfo(changeNull(edu.getEducationInfo()));
					fw_edu.write(cvedu.write2Line(cvedu) + "\r\n");
					fw_edu.flush();
				}
			}

			// 工作信息
			if (map.getJobs() != null) {
				List<Job> jobs = map.getJobs();
				for (Job job : jobs) {
					CvJob cvjob = new CvJob();
					cvjob.setCandidateid(candidateid);
					cvjob.setStartTime(changeNull(job.getStartTime()));
					cvjob.setEndTime(changeNull(job.getEndTime()));
					cvjob.setCompany(changeNull(job.getCompany()));
					cvjob.setDepartment(changeNull(job.getDepartment()));
					cvjob.setTitle(changeNull(job.getTitle()));
					cvjob.setReport(changeNull(job.getReport()));
					cvjob.setSalary(changeNull(job.getSalary()));
					cvjob.setMember(changeNull(job.getMember()));
					cvjob.setDuty(changeNull(job.getDuty()));
					cvjob.setAchieve(changeNull(job.getAchieve()));
					cvjob.setReason(changeNull(job.getReason()));
					cvjob.setCity(changeNull(job.getCity()));
					cvjob.setInfo(changeNull(job.getInfo()));
					cvjob.setJobInfo(changeNull(job.getJobInfo()));
					fw_job.write(cvjob.write2Line(cvjob) + "\r\n");
					fw_job.flush();
				}
			}

			// 项目信息
			if (map.getProjects() != null) {
				List<Project> pros = map.getProjects();
				for (Project pro : pros) {
					CvProject cvpro = new CvProject();
					cvpro.setCandidateid(candidateid);
					cvpro.setStartTime(changeNull(pro.getStartTime()));
					cvpro.setEndTime(changeNull(pro.getEndTime()));
					cvpro.setProjectName(changeNull(pro.getName()));
					cvpro.setCompany(changeNull(pro.getCompany()));
					cvpro.setContent(changeNull(pro.getContent()));
					cvpro.setDuty(changeNull(pro.getDuty()));
					cvpro.setAchieve(changeNull(pro.getAchieve()));
					cvpro.setCity(changeNull(pro.getCity()));
					cvpro.setInfo(changeNull(pro.getInfo()));
					cvpro.setProjectInfo(changeNull(pro.getProjectInfo()));
					fw_pro.write(cvpro.write2Line(cvpro) + "\r\n");
					fw_pro.flush();

				}
			}

			// 技能信息
			if (map.getSkills() != null) {
				List<Skill> skills = map.getSkills();
				for (Skill sk : skills) {
					CvSkill cvsk = new CvSkill();
					cvsk.setCandidateid(candidateid);
					cvsk.setSkillName(changeNull(sk.getSkillName()));
					cvsk.setInfo(changeNull(sk.getInfo()));
					cvsk.setSkillInfo(changeNull(sk.getSkillInfo()));
					cvsk.setSkillExperience(sk.getSkillExperience());
					fw_skill.write(cvsk.write2Line(cvsk) + "\r\n");
					fw_skill.flush();

				}
			}

			// 自我评价
			if (map.getComments() != null) {
				List<Comment> coms = map.getComments();
				for (Comment com : coms) {
					CvComment cvcom = new CvComment();
					cvcom.setCandidateid(candidateid);
					cvcom.setInfo(changeNull(com.getInfo()));
					cvcom.setCommentInfo(changeNull(com.getCommentInfo()));
					fw_com.write(cvcom.write2Line(cvcom) + "\r\n");
					fw_com.flush();

				}
			}

			// 开关读写
			if (candidateid % 10000 == 9999) {

				fw_cv.close();
				fw_basic.close();
				fw_exp.close();
				fw_edu.close();
				fw_job.close();
				fw_pro.close();
				fw_skill.close();
				fw_com.close();
				fw_credit.close();
				fw_erro.close();

				fw_cv = new FileWriter(pa_cv, true);
				fw_basic = new FileWriter(pa_basic, true);
				fw_exp = new FileWriter(pa_exp, true);
				fw_edu = new FileWriter(pa_edu, true);
				fw_job = new FileWriter(pa_job, true);
				fw_pro = new FileWriter(pa_pro, true);
				fw_skill = new FileWriter(pa_skill, true);
				fw_com = new FileWriter(pa_com, true);
				fw_credit = new FileWriter(pa_credit, true);
				fw_erro = new FileWriter(pa_erro, true);

			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public static String changeNull(String str) {
		try {

			if (str == null)
				str = "\\N";
			else if (str == "\\N") {
				return str;
			} else {
				str = replaceTab(str);
				str = new String(str.getBytes("gbk"), "gb2312").toString().replace("\\", ",").replace("?", "")
						.replace("？", "");
				str = str.trim().equals("") ? "\\N" : str;
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "\\N";
		}
		return str;
	}

	/* 去除制表符 */
	public static String replaceTab(String str) {
		String dest = "";
		try {
			if (str != null) { // \\s*|\t|\r|\n \t
				Pattern p = Pattern.compile("\\s*|\t|\r|\n");
				Matcher m = p.matcher(str);
				dest = m.replaceAll("");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dest;
	}

}
